package com.atqh.srrt.chicken.handle;

import com.alibaba.fastjson.JSON;
import com.atqh.srrt.chicken.Multithreading.UserThreadLocal;
import com.atqh.srrt.chicken.domain.SysUser;
import com.atqh.srrt.chicken.service.LoginService;
import com.atqh.srrt.chicken.utils.ErrorCode;
import com.atqh.srrt.chicken.utils.Result;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @作者：大叔azhe
 * @api：详细描述
 * @创建时间：8:48 2022/8/16
 */
@Component
//lombok自带的log打印
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;

    /**
    *@作者：大叔azhe
    *@api：preHandle
     * 调用时间：Controller方法处理之前
     *
     * 执行顺序：链式Intercepter情况下，Intercepter按照声明的顺序一个接一个执行
     *
     * 若返回false，则中断执行，注意：不会进入afterCompletion
    *@创建时间：21:01 2023/1/3
    */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            //handler 可能是 RequestResourceHandler springboot 程序 访问静态资源 默认去classpath下的static目录去查询
            return true;
        }
        String token = request.getHeader("Authorization");


        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");


        if (StringUtils.isBlank(token)) {
            Result result = Result.Fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        SysUser sysUser = loginService.checkToken(token);
        if (sysUser==null){
            Result result = Result.Fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        log.info("用户为{}",sysUser);
//        将登陆用户添加到本地线程池

        UserThreadLocal.put(sysUser);

        log.info("登录的用户为{}",
                UserThreadLocal.get());
        return true;
    }

    /**
    *@作者：大叔azhe
    *@api：afterCompletion
     * 调用前提：preHandle返回true
     *
     * 调用时间：DispatcherServlet进行视图的渲染之后
     *
     * 多用于清理资源,在每次访问完配置好的需要拦截的接口的controller结束后，都会清空一遍线程池
     *
    *@创建时间：21:10 2023/1/3
    */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("登录的用户{}从线程池里被删除了",UserThreadLocal.get());
        /**
        *@作者：大叔azhe
        *@api：如果不删除，会有内存泄露风险,因为jvm的原因，强弱引用被删除时机不同，容易导致弱引用的key被删除了，但value是强引用，永远留在了内存中
        *@创建时间：10:29 2022/8/18
        */
        UserThreadLocal.remove();
    }
}
